<template>
  <div class="custom">
    <template v-if="isCustom?.businessID === CHAT_MSG_CUSTOM_TYPE.SERVICE">
      <div>
        <h1>
          <label>{{ extension.title }}</label>
          <a v-if="extension.hyperlinks_text" :href="extension.hyperlinks_text.value" target="view_window">{{
            extension.hyperlinks_text.key }}</a>
        </h1>
        <ul v-if="extension.item && extension.item.length > 0">
          <li v-for="(item, index) in extension.item" :key="index">
            <a v-if="isUrl(item.value)" :href="item.value" target="view_window">{{ item.key }}</a>
            <p v-else>
              {{ item.key }}
            </p>
          </li>
        </ul>
        <article>{{ extension.description }}</article>
      </div>
    </template>
    <template v-else-if="isCustom?.businessID === CHAT_MSG_CUSTOM_TYPE.EVALUATE">
      <div class="evaluate">
        <!-- <h1>{{ TUITranslateService.t("message.custom.对本次服务评价") }}</h1> -->
        <!-- <ul class="evaluate-list">
					<li v-for="(item, index) in Math.max(isCustom.score, 0)" :key="index" class="evaluate-list-item">
						<Icon :file="star" class="file-icon" />
					</li>
				</ul> -->
        <!-- <article>{{ isCustom.comment }}</article> -->
        <view>您好，如您方便，请您为我本次服务作出评价，期待您的评价与意见，谢谢！</view>
        <view class="evaluated" v-if="message && message.isModified">
          <img src="../../../../assets/icon/check.png" />
          <view>感谢您对本次服务作出的评价！</view>
        </view>
        <view class="evaluate_emo" v-else>
          <view class="item" @click="evaluateFun(message, 5)">
            <img src="../../../../assets/icon/haoping.png" />
            <text>好评</text>
          </view>
          <view class="item" @click="evaluateFun(message, 3)">
            <img src="../../../../assets/icon/zhongping.png" />
            <text>一般</text>
          </view>
          <view class="item" @click="evaluateFun(message, 2)">
            <img src="../../../../assets/icon/chaping.png" />
            <text>差评</text>
          </view>
        </view>
      </div>
    </template>
    <template v-else-if="isCustom?.businessID === CHAT_MSG_CUSTOM_TYPE.ORDER">
      <div class="order" @click="openLink(isCustom.link)">
        <img :src="isCustom.imageUrl">
        <main>
          <h1>{{ isCustom.title }}</h1>
          <p>{{ isCustom.description }}</p>
          <span>{{ isCustom.price }}</span>
        </main>
      </div>
    </template>
    <template v-else-if="isCustom?.businessID === CHAT_MSG_CUSTOM_TYPE.LINK">
      <div class="textLink">
        <p>{{ isCustom.text }}</p>
        <a :href="isCustom.link" target="view_window">{{
          TUITranslateService.t("message.custom.查看详情>>")
          }}</a>
      </div>
    </template>
    <template v-else-if="isCustom?.businessID === 'imgMsg'">
      <div class="textLink">
        <span v-html="isCustom.ext" />
        <el-image style="width: 120px; height: 80px; border-radius: 6px;" :src="isCustom.imageUrl"
          :preview-src-list="[isCustom.imageUrl]" fit="cover" v-if="isCustom.imageUrl" />
      </div>
    </template>
    <template v-else-if="isCustom?.businessID === 'docMsg'">
      <div class="textLink">
        <MessageFile :content='isCustom' :messageItem="isCustom" />
      </div>
    </template>
    <template v-else-if="isCustom?.businessID === 'workOrder'">
      <div class="work-order" @click="openDetail(isCustom.id)">
        <img src="../../../../assets/icon/work-order2.png" />
        <ul>
          <li v-if="isCustom.status == 1">工单初审中</li>
          <li v-if="isCustom.status == 2">工单已完结</li>
          <li>工单名称：{{ isCustom.title }}</li>
          <li>工单类型：{{ isCustom.cate_name }}</li>
          <li>预计完成时间：{{ isCustom.plan_time }}</li>
        </ul>
      </div>
    </template>
    <template v-else-if="isCustom?.businessID === 'payOrder'">
      <div class="work-order" @click="openOrderDetail(isCustom.id)">
        <img src="../../../../assets/icon/pay-order2.png" />
        <ul>
          <li v-if="isCustom.status == 0">支付费用-待支付</li>
          <li v-if="isCustom.status == 1">支付费用-已支付</li>
          <li>支付内容：{{ isCustom.product }}</li>
          <li>支付金额：{{ isCustom.total_price }}元</li>
          <li style="font-weight: normal;" v-if="isCustom.status == 0">点击支付费用</li>
        </ul>
      </div>
    </template>
    <template v-else>
      <span v-html="content.custom" />
    </template>
  </div>
  <WorkOrderDetail :visible="isVisible" :woId="currnetId" @closeDialog="closeDialog" />
  <el-dialog v-model="showPayDialog" title="支付订单" width="500px" :close-on-click-modal="false">
    <div class="payBox" v-if="showPayType">
        <div class="payItem" v-for="(item, index) in payArr" :key="index" @click="payIndex = index"
            :class="payIndex == index ? 'selectPay' : ''">
            <div style="flex: 1;">
                <img src="@/assets/image/zxl/wx_icon.png" v-if="item.value == 1" class="payIcon"></img>
                <img src="@/assets/image/zxl/zfb_icon.png" v-if="item.value == 2" class="payIcon"></img>
            </div>
            <span>{{ item.label }}</span>
        </div>
        <el-button type="primary" @click="confirmBuy" :loading="addPayLoading" :disabled="addPayLoading">立即支付</el-button>
    </div>
    <div class="showBox" v-if="!showPayType">
        <div class="headTip">
            <span class="texts">使用{{ payIndex == 0 ? '微信' : '支付宝' }}扫码支付，支付倒计时：</span>
            <el-countdown :value="valueTime" value-style="texts" @finish="endTime" />
        </div>
        <el-image style="width: 200px; height: 200px" :src="orderInfo.code_url" fit="fill" />
        <span style="margin-top: 24px;">支付内容：{{orderInfo.order.product}}</span>
        <span style="margin-top: 5px;">{{ orderInfo.order.order_type == '3' ? '分钟数' : '数量'}}：{{orderInfo.order.product_num}}{{ orderInfo.order.order_type == '3' ? '分钟' : '次' }}</span>
        <span style="margin-top: 5px; margin-bottom: 24px;">支付金额：{{orderInfo.amount}}元</span>
        <div v-if="isChecking" class="loading">
            <span class="spinner"></span>
            <p>等待支付确认中...</p>
        </div>
        <div v-if="paymentSuccess" class="success-message">
            <i class="icon-success"></i>
            <h3>支付成功！</h3>
        </div>
    </div>
  </el-dialog>
  <el-dialog v-model="showPayStatus" title="支付订单" width="400px">
    <div class="pay_status success" v-if="payStatus == 1">
      <el-icon :size="70" color="#01509f"><SuccessFilled /></el-icon>
      <div class="pay_status_text">订单已支付</div>
    </div>
    <div class="pay_status fail" v-if="payStatus == 4">
      <el-icon :size="70" color="#666"><CircleCloseFilled /></el-icon>
      <div class="pay_status_text">订单已过期</div>
    </div>
  </el-dialog>
  <el-dialog v-model="showOrderDetail" title="订单详情" width="800px">
    <el-descriptions title="" border :column="1">
      <el-descriptions-item label="需要支付的内容">{{orderDetail?.product}}<span v-if="orderDetail?.cate_name"> - {{orderDetail?.cate_name}}</span></el-descriptions-item>
      <el-descriptions-item :label="orderDetail?.unit == '次' ? '数量' : '分钟数'">{{orderDetail?.product_num}}{{orderDetail?.unit}}</el-descriptions-item>
      <el-descriptions-item label="费用金额">{{orderDetail?.total_price}}</el-descriptions-item>
      <el-descriptions-item label="备注">{{orderDetail?.mark}}</el-descriptions-item>
      <el-descriptions-item label="发起支付的法务">{{orderDetail?.creator_name}}</el-descriptions-item>
      <el-descriptions-item label="发起时间">{{orderDetail?.create_time}}</el-descriptions-item>
      <el-descriptions-item label="支付状态">
        <el-tag type="danger" v-if="orderDetail?.status == 0">未支付</el-tag>
        <el-tag type="success" v-if="orderDetail?.status == 1">已支付</el-tag>
        <el-tag type="warning" v-if="orderDetail?.status == 4">已过期</el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="支付时间" v-if="orderDetail?.status == 1">{{orderDetail?.pay_time}}</el-descriptions-item>
    </el-descriptions>
    <div class="dialog-footer">
      <el-button @click="showOrderDetail = false">关闭</el-button>
      <el-button type="primary" @click="openPayDetail(orderDetail?.id)" v-if="orderDetail?.status == 0">立即支付</el-button>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { UserEva } from '@/api';
import { CheckPay, GetOrder, OrderPay } from '@/api/order';
import { IConversationModel, IMessageModel, SendMessageOptions, SendMessageParams, StoreName, TUIChatEngine, TUIChatService, TUIStore, TUITranslateService } from '@tencentcloud/chat-uikit-engine';
import { reactive, ref, watch, watchEffect } from '../../../../adapter-vue';
import { CHAT_MSG_CUSTOM_TYPE } from '../../../../constant';
import { ICustomMessagePayload } from '../../../../interface';
import { isUrl, JSONToObject } from '../../../../utils/index';
import WorkOrderDetail from '../../../common/WorkOrder/index';
import OfflinePushInfoManager, { IOfflinePushInfoCreateParams } from '../../offlinePushInfoManager/index';
import { sendMessages } from '../../utils/sendMessage';
import { isEnabledMessageReadReceiptGlobal } from '../../utils/utils';
import MessageFile from './message-file.vue';

interface Props {
  messageItem: IMessageModel;
  content: any;
}

interface Order {
    id:                number;
    order_sn:          string;
    user_id:           number;
    company_id:        number;
    mobile:            string;
    product:           string;
    product_id:        number;
    product_num:       number;
    total_price:       string;
    pay_price:         string;
    order_type:        string;
    paid:              number;
    pay_time:          null;
    pay_type:          number;
    create_time:       Date;
    status:            number;
    mark:              string;
    remark:            null;
    admin_mark:        null;
    transaction_id:    null;
    mer_id:            number;
    reconciliation_id: number;
    is_del:            number;
    is_system_del:     number;
    refund_switch:     number;
    pay_data:          null;
    delivery_time:     null;
    update_time:       null;
    out_trade_no:      null;
    extra_id:          number;
    group_id:          number;
}

interface OrderDetail {
  id: string;
  product: string;
  total_price: string;
  mark: string;
  creator_name: string;
  create_time: string;
  status: number;
  product_num: number;
  unit: string;
  cate_name: string;
  pay_time: string;
}

const props = withDefaults(defineProps<Props>(), {
  messageItem: undefined,
  content: undefined,
});

const custom = ref();
const message = ref<IMessageModel>();
const extension = ref();
const isCustom = ref<ICustomMessagePayload>();
const isVisible = ref(false);
const currnetId = ref('')

const showPayDialog = ref(false);
const showPayType = ref(true);
const payArr = ref([{
    label: '微信支付',
    value: 1
}, {
    label: '支付宝支付',
    value: 2
}])
const payIndex = ref(0)
const valueTime = ref(0)
const isChecking = ref(false);
const paymentSuccess = ref(false);
const checkTimer = ref<number>(0);
const orderInfo = reactive({
  amount: '',
  code_url: '',
  out_trade_no: '',
  order: {} as Order
})
const addPayLoading = ref(false);

const showPayStatus = ref(false)
const payStatus = ref(0)

const showOrderDetail = ref(false);
const orderDetail = ref<OrderDetail>()
const currentConversation = ref<IConversationModel>();

TUIStore.watch(StoreName.CONV, {
  currentConversation: (conversation: IConversationModel) => {
    currentConversation.value = conversation;
  },
});

watchEffect(() => {
  custom.value = props.content;
  message.value = props.messageItem;
  const { payload } = props.messageItem;
  isCustom.value = payload.data || '';
  isCustom.value = JSONToObject(payload.data);
  if (payload.data === CHAT_MSG_CUSTOM_TYPE.SERVICE) {
    extension.value = JSONToObject(payload.extension);
  }
});

watch(
	() => showPayDialog.value,
	newVal => {
		if (newVal == false) {
			showPayType.value = true;
			payIndex.value = 0;
			valueTime.value = 0;
			isChecking.value = false;
			paymentSuccess.value = false;
      orderInfo.amount = '';
      orderInfo.code_url = '';
      orderInfo.out_trade_no = '';
      orderInfo.order = {} as Order;
			clearInterval(checkTimer.value);
		}
	}
)

const openLink = (url: any) => {
  window.open(url);
};

function openDetail(e: any) {
  isVisible.value = true
  currnetId.value = e.toString()
}

const openPayDetail = (e: any) => {
  showOrderDetail.value = false
  CheckPay({
    id: e
  }).then(res => {
    if(res.status == 0) {
      showPayDialog.value = true
    } else {
      showPayStatus.value = true
      payStatus.value = res.status
    }
  })
}

function openOrderDetail(e: any) {
  showOrderDetail.value = true
  GetOrder({
    id: e
  }).then((res: any) => {
    orderDetail.value = res.data
  })
}

const confirmBuy = async () => {
    addPayLoading.value = true;
    if(isCustom.value && isCustom.value.id) {
      OrderPay({
      id: isCustom.value.id,
      type: payArr.value[payIndex.value].value
    }).then(res => {
      addPayLoading.value = false;
      showPayType.value = false;
      orderInfo.code_url = res.data.code_url;
      orderInfo.out_trade_no = res.data.out_trade_no;
      orderInfo.amount = res.data.amount;
      orderInfo.order = res.data.order;
      valueTime.value = Date.parse(orderInfo.order.create_time.toString()) + 1000 * 60 * 60 * 2;
      startCheckingPayment();
    })
    }
    
}

function closeDialog() {
  isVisible.value = false
  currnetId.value = ''
}

const endTime = () => {
    clearInterval(checkTimer.value);
    showPayDialog.value = false;
    isChecking.value = false;
}

const startCheckingPayment = () => {
    isChecking.value = true;
    // 立即检查一次

    // 然后每隔3秒检查一次，避免过于频繁
    checkTimer.value = setInterval(checkPayment, 3000);
};

// 检查支付状态
const checkPayment = async () => {
    CheckPay({
      id: isCustom.value?.id
    }).then(res => {
      if (res.status == 1) {
        handlePaymentSuccess(res.data);
      }
    })
};

const handlePaymentSuccess = (content: any) => {
    isChecking.value = false;
    paymentSuccess.value = true;
    clearInterval(checkTimer.value);

    // 3秒后跳转到订单详情页
    setTimeout(() => {
        showPayDialog.value = false
        sendPayMsg(content)
        // 这里可以使用vue-router进行跳转
        // router.push(`/order/detail/${orderId.value}`);
    }, 2000);
};

const sendPayMsg = (content: any) => {
  const payload = {
    data: JSON.stringify({
      businessID: 'payOrder',
      ...content
    })
  };
  const options = {
    to:
      currentConversation?.value?.groupProfile?.groupID
      || currentConversation?.value?.userProfile?.userID,
    conversationType: currentConversation?.value?.type,
    payload,
    needReadReceipt: isEnabledMessageReadReceiptGlobal(),
  };
  const offlinePushInfoCreateParams: IOfflinePushInfoCreateParams = {
    conversation: currentConversation.value,
    payload: options.payload,
    messageType: TUIChatEngine.TYPES.MSG_CUSTOM,
  };
  const sendMessageOptions: SendMessageOptions = {
    offlinePushInfo: OfflinePushInfoManager.create(offlinePushInfoCreateParams),
  };
  TUIChatService.sendCustomMessage(options as SendMessageParams, sendMessageOptions).then(async res => {
    const msg = [{
      payload: {
        text: '订单已支付，请及时处理'
      },
      type: 'text'
    }]
    await sendMessages(
      msg,
      currentConversation.value,
    );
  })
};

function evaluateFun(msg: any, score: any) {
  if (!msg.isModified) {
    if(message.value && message.value.ID) {
      const messageModel = TUIStore.getMessageModel(message.value.ID);
      let data = JSON.parse(msg.payload.data);
      data.isEvaluated = true;
      msg.payload.data = JSON.stringify(data);
      let promise = messageModel.modifyMessage(msg);
      UserEva({
        sign: data.sign,
        content: score == 5 ? '满意' : (score == 3 ? '一般' : '不满意'),
        score: score
      }).then(res => {
        console.log(res)
      })
      promise.catch((error) => {
        console.error(error)
      });
    }
  }
}
</script>
<style lang="scss" scoped>
@import "../../../../assets/styles/common";

a {
  color: #679ce1;
}

.custom {
  font-size: 14px;

  h1 {
    font-size: 14px;
    color: #000;
  }

  h1,
  a,
  p {
    font-size: 14px;
  }

  .evaluate {
    ul {
      display: flex;
      padding: 10px 0;
    }

    &-list {
      display: flex;
      flex-direction: row;

      &-item {
        padding: 0 2px;
      }
    }

    .tip {
      font-size: 12px;
      color: #999;
      margin-top: 10px;
    }

    .evaluated {
      display: flex;
      align-items: center;
      margin-top: 10px;

      img {
        width: 20px;
        height: 20px;
        margin-right: 10px;
      }
    }

    .evaluate_emo {
      display: flex;
      justify-content: space-between;
      margin-top: 10px;

      .item {
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        cursor: pointer;

        img {
          width: 40px;
          height: 40px;
        }

        text {
          font-size: 14px;
          color: #666;
          margin-top: 10px;
        }
      }
    }
  }

  .order {
    display: flex;

    main {
      padding-left: 5px;

      p {
        font-family: PingFangSC-Regular;
        width: 145px;
        line-height: 17px;
        font-size: 14px;
        color: #999;
        letter-spacing: 0;
        margin-bottom: 6px;
        word-break: break-word;
      }

      span {
        font-family: PingFangSC-Regular;
        line-height: 25px;
        color: #ff7201;
      }
    }

    img {
      width: 67px;
      height: 67px;
    }
  }

  .work-order {
    display: flex;
    align-items: center;
    cursor: pointer;
    min-width: 240px;

    img {
      width: 50px;
      height: 50px;
      margin-right: 10px;
    }

    li {
      font-size: 14px;
      font-weight: bold;
      line-height: 28px;
    }
  }
}

.payBox {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 320px;

    .selectPay {
        border: 1px solid #01509f !important;
    }

    .payItem {
        width: 400px;
        padding: 25px;
        box-sizing: border-box;
        border-radius: 6px;
        border: 1px solid #eaeaea;
        margin-bottom: 16px;
        display: flex;
        align-items: center;
        font-size: 18px;
        font-weight: bolder;
        color: #333;
        cursor: pointer;

        .payIcon {
            width: 48px;
            height: 48px;
            flex-shrink: 0;
        }
    }

    .buyBtn {
        width: 146px;
        height: 36px;
        border-radius: 6px;
        box-sizing: border-box;
        text-align: center;
        line-height: 36px;
        color: #fff;
        background-color: #01509f;
        font-size: 16px;
        margin-top: 24px;
    }
}

.showBox {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .headTip {
        display: flex;
        align-items: center;
        color: #333;
        font-size: 16px;
        font-weight: normal;
        margin-bottom: 24px;

        :deep(.el-statistic__content) {
            font-size: 16px;
        }

        :deep(.el-statistic__number) {
            color: #333;
            font-size: 16px;
            font-weight: normal;
        }
    }
}

.pay_status{
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px 0;

  &.success{
    color: #01509f;
  }

  &.fail{
    color: #666;
  }
  
  .pay_status_text{
    margin-top: 10px;
  }


}

.dialog-footer{
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
}
</style>
